package com.ceba.test.modules.email.logicService;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ceba.test.base.config.LogicPathUtil;
import com.ceba.test.base.enums.FileTypeEnum;
import com.ceba.test.modules.email.entity.EmailEntity;
import com.ceba.test.modules.email.entity.EmailRelationFile;
import org.apache.commons.collections.CollectionUtils;


public class HtmlFileEmail extends BaseEmailMannager{

	public HtmlFileEmail(EmailEntity emailEntity) {
		super(emailEntity);
	}

	@Override
	public String subject() {
		return super.getEmailEntity().getSubject();
	}

	@Override
	public String content() {
		EmailEntity emailEntity=super.getEmailEntity();
		List<String> pathList=indexImgPath(emailEntity);
		for(String path:pathList){
			EmailRelationFile file = new EmailRelationFile(null, path, FileTypeEnum.HTML);
			if(emailEntity.getFileList() == null){
				emailEntity.setFileList(new ArrayList<>());
			}
			emailEntity.getFileList().add(file);
		}
		return emailEntity.getContent();
	}

	private List<String> indexImgPath(EmailEntity emailEntity) {
		// 索引mailBody中的图片路径
		String content=emailEntity.getContent();
		List<String> imagePathList=new ArrayList<>();
		List<String> pathList = htmlFilePath(content);
		if (CollectionUtils.isNotEmpty(pathList)) {
			for (String imagePath : pathList) {
				// imagePath.indexOf(SubjectUtils.getUserId()) != -1 ||
				//文件管理修改--个性签名
				String getFilePath = LogicPathUtil.getBrowserPathToAbsolutelyPath(imagePath);
				content = content.replace(imagePath, getFilePath);
				imagePathList.add(getFilePath);
			}
		}
		emailEntity.setContent(content);
		return imagePathList;
	}
	
	private List<String> htmlFilePath(String str) {
		List<String> resultList = new ArrayList<>();
		String regx = "(?<=(src=\"))[.\\s\\S]*?(?=(\"))";
		// 1.将正在表达式封装成对象Patten 类来实现
		Pattern pattern = Pattern.compile(regx);
		// 2.将字符串和正则表达式相关联
		Matcher matcher = pattern.matcher(str);
		// 3.String 对象中的matches 方法就是通过这个Matcher和pattern来实现的。
		// 查找符合规则的子串
		while (matcher.find()) {
			resultList.add(matcher.group());
		}
		return resultList;
	}
}
